package com.tsm.picachu.level.ui;

import java.util.Timer;
import java.util.TimerTask;

import com.tsm.picachu.GeneralActivity;
import com.tsm.picachu.R;
import com.tsm.picachu.common.Constant;
import com.tsm.picachu.common.Utils;
import com.tsm.picachu.data.User;
import com.tsm.picachu.gameplay.ui.GamePlayActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class SelectLevelActivity extends GeneralActivity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_select_level);

		String username = getIntent().getStringExtra(Constant.EXTRA_USERNAME);

		final User user = Utils.getUserData(this, username);

		for (int level = 0; level < user.getLevel(); level++)
		{
			ImageButton levelButton = (ImageButton) findViewById(R.id.level_1
					+ level);

			levelButton.setImageResource(R.drawable.level1 + 2 * level);

			final int levelValue = level + 1;

			levelButton.setOnClickListener(new OnClickListener()
			{
				public void onClick(View v)
				{
					Intent intent = new Intent(SelectLevelActivity.this,
							GamePlayActivity.class);
					intent.putExtra(Constant.EXTRA_CURRENT_LEVEL, levelValue);

					if (user.getLevel() > levelValue)
					{
						intent.putExtra(Constant.EXTRA_CURRENT_MINI_LEVEL, 1);
					}
					else
					{
						intent.putExtra(Constant.EXTRA_CURRENT_MINI_LEVEL,
								user.getMiniLevel());
					}

					startActivity(intent);
				}
			});
		}

		processImageOppa();
	}

	private void processImageOppa()
	{
		final View oppaView = findViewById(R.id.select_level_oppa);

		TimerTask timerTask = new TimerTask()
		{
			private boolean isFirstBg = true;

			@Override
			public void run()
			{
				runOnUiThread(new Runnable()
				{
					public void run()
					{
						if (isFirstBg)
						{
							oppaView.setBackgroundResource(R.drawable.oppa1);
						}
						else
						{
							oppaView.setBackgroundResource(R.drawable.oppa2);
						}

						isFirstBg = !isFirstBg;
					}
				});
			}
		};

		Timer timer = new Timer();
		timer.schedule(timerTask, 0, Constant.TIME_ANIM_LEVEL);
	}
}
